import json
import queue
import ssl
import threading
import uuid

import requests

lock = threading.Lock()


class MyThread(threading.Thread):
    def __init__(self, threadId):
        super().__init__()
        self.threadId = threadId

    def run(self):
        name = str(uuid.uuid1()) + ".jpg"
        params = {"dl": name}
        lock.acquire()
        url = urlQueue.get()
        lock.release()
        print("当前线程: {}, 请求url: {}".format(self.threadId, url))
        req = requests.get(url, params, verify=False)
        print(req.url)
        with open(r"C:/Users/e-Xingfu.Yang/Desktop/Tmp/spider/{}".format(name), "wb") as f:
            f.write(req.content)


class download:
    def __init__(self, server=None, page=1, per_page=10, target=None):
        self.server = server
        self.target = target
        self.page = page
        self.per_page = per_page

    def getImageUrl(self):
        ssl._create_default_https_context = ssl._create_unverified_context
        params = {"page": self.page, "per_page": self.per_page, "search-quality-boosting": "Acontrol"}
        req = requests.get(url=self.target, params=params, verify=False)
        res = json.loads(req.content)
        for re in res:
            urls = re["urls"]
            urlQueue.put(urls["full"])

    def downloadImag(self):
        threads = []
        for i in range(5):
            th = MyThread(threadId=i)
            th.start()
            threads.append(th)
        for th in threads:
            th.join()


urlQueue = queue.Queue(30)
if __name__ == "__main__":
    print()
    dl = download(target="https://unsplash.com/napi/topics/wallpapers/photos")
    for i in range(2):
        dl.page += 1
        dl.getImageUrl()
    dl.downloadImag()
